
	$(document).ready(function () {
		
		setType();
		arrears();
		$("#customerName").combobox({
		onChange: function (n,o) {

			$("#customerPhone").textbox("clear");
			$("#customerHybh").textbox("clear");
			searchCus();
		}

		});
		$("#customerPhone").combobox({

			onChange: function (n,o) {

				$("#customerName").textbox("clear");
				$("#customerHybh").textbox("clear");
				searchCus();
			}

			});
		$("#customerHybh").combobox({

			onChange: function (n,o) {

				$("#customerName").textbox("clear");
				$("#customerPhone").textbox("clear");
				searchCus();
			}

			});
		
		var hybh=$('#customerHybh').val();
		var name=$('#customerName').val();
		var phone=$('#customerPhone').val();
		
		if(hybh==''&&name==''&&phone==''){
			return false;
		}
//		setLc();
		
//		$("#buyProduct").datagrid('addEditor',[ //添加cardNo列editor
//		    	                                {field:'number',editor:{
//		    	                                type:'numberspinner',
//		    	                                min:1,
//												max:100,
//												options:{
//												min:1,
//												 onChange : function(n){
//													 sum(n);
//												}
//												}
//		    	                                }
//		    	                                }]
//		    );
		//$("#buyProduct").datagrid('removeEditor','number');
		searchCus();
	})		
//			//扩展datagrid:动态添加删除editor
//			$.extend($.fn.datagrid.methods, { 
//			addEditor : function(jq, param) { 
//			if (param instanceof Array) { 
//			$.each(param, function(index, item) { 
//			var e = $(jq).datagrid('getColumnOption', item.field); 
//			e.editor = item.editor; }); 
//			} else { 
//			var e = $(jq).datagrid('getColumnOption', param.field); 
//			e.editor = param.editor; 
//			} 
//			}, 
//			removeEditor : function(jq, param) { 
//			if (param instanceof Array) { 
//			$.each(param, function(index, item) { 
//			var e = $(jq).datagrid('getColumnOption', item); 
//			e.editor = {}; 
//			}); 
//			} else { 
//			var e = $(jq).datagrid('getColumnOption', param);
//			e.editor = {}; 
//			} 
//			}
//			});
	
	
			//获取产品类别
			function  setType()
			{
					var com=$('#selType_combobox');
					com.combobox({
							url: 'buyProduct/selProCode2',
						  valueField:'ids', 
						  textField:'name',
						  onSelect: function(row) 
							{	
								setCombobox(row.ids);
							} 
					});
					
		
			}
			//获取产品列表放入下拉
			function  setCombobox(typeIds)
			{	
				var url='/buyProduct/selProduct';
				var data={"typeIds":typeIds};
				var reData = common_ajax.ajaxFunc(url,data);
				var daJson=$.parseJSON(reData);
				var com=$('#addPro_combobox');
				com.combobox({
					  data:daJson,
					  valueField:'ids', 
					  textField:'probh',
					  filter: function(q, row){ 
					        var opts = $(this).combobox('options'); 
					       // .toUpperCase()小写转大写   toLowerCase()大写转小写
					        return row[opts.textField].toLowerCase().indexOf(q.toLowerCase()) >= 0;//同一转换成小写做比较，这里改成>=即可在任意地方匹配  
					   },
					  formatter: function(row)
					  {		
						  var opts = $(this).combobox('options');
						  row[opts.textField]=row.probh+"("+row.name+")";
						  return    row[opts.textField];
					  },
					  onSelect: function(row) 
						{	
							getProduct(row.ids);
						} 
				});
				
			}
//			//获取顾客信息
			function searchCus(){
				
				var reData=getCusInfo();
				if(reData.msg==200){
					//清空表格
					var rows = $('#buyProduct').datagrid('getRows');
	                for (var i = 0; i <rows.length; i++) {
	                    var index = $('#buyProduct').datagrid('getRowIndex', rows[i]);
	                    $('#buyProduct').datagrid('deleteRow', index);
	                }
	                $('#buyProduct').datagrid('loadData', { total: 0, rows: [] });
	                $('#addPro_combobox').combobox('setValues',"");
	                
	                var url='/buyProduct/getLcByCus';
					var data={"customerIds":reData.customer.ids};
					var result = common_ajax.ajaxFunc(url,data,"json");
					if(result!=null && result.msg==200){
						 $('#buyProduct').datagrid('insertRow',{row:result.lcMap});
						 $("#receivable").val(parseFloat(result.lcMap.total));
						 ysk();
					}
				}
			}
			
			
			$(document).keydown(function(event){ 
				if(event.keyCode == 13){
					getCusInfo();
				} 
			}); 
			var editIndex = undefined;
			function endEditing(obj){
				if (editIndex == undefined){return true}
				if (obj.datagrid('validateRow', editIndex)){
						obj.datagrid('endEdit', editIndex);
					editIndex = undefined;  
					return true;
				} else {
					return false;
				}
			}
			function onClickRow(index){
				
				if (editIndex != index){
					if (endEditing($(this))){
						$(this).datagrid('selectRow', index);
						$(this).datagrid('beginEdit', index);
						editIndex = index;
					} else {
						$('#buyProduct').datagrid('selectRow', editIndex);
					}
				}
				
			}
			/*删除数据表格行操作*/
			function  go(val,row){
				return "<a href='#'  class='button-delete button-danger  l-btn l-btn-small' onclick='deleterow(this)' ><span class='l-btn-left' ><span class='l-btn-text'>删除</span></span></a>";
			} 
			function getRowIndex(target){
				var tr = $(target).closest('tr.datagrid-row');
				return parseInt(tr.attr('datagrid-row-index'));
			}
			function deleterow(target){
				parent.$.messager.confirm('Confirm','确定删除？',function(r){
					if (r){
						var row = $('#buyProduct').datagrid('getSelected');
						var index=$('#buyProduct').datagrid('getRowIndex', row);
						$('#buyProduct').datagrid('deleteRow', index);
//						$('#buyProduct').datagrid('deleteRow', getRowIndex(target));
						ysk();
						
					}
				});
			}
			
			//清除筛选条件
			function clearsj(){
				$("#customerName").textbox("clear");
				$("#customerPhone").textbox("clear");
				$("#customerHybh").textbox("clear");
				$("#cpbh").textbox("clear");
				$('#cpbh').textbox('textbox').attr('readonly',false);
				
			}
// 			-------------------------
			//选中产品编号后查出产品
			function getProduct(proIds)
			{	
				//获取所有
				var url="/buyProduct/getProByIds";
				var data={"ids":proIds};
				var reData = common_ajax.ajaxFunc(url, data,"json");
//				var reDataJson = JSON.parse(reData);
				var row = $('#buyProduct').datagrid('getSelected');
				if(reData.msg==200)
				{	
					if(!isHave(reData.mode.probh))
					{
						reData.mode.number='1';
						reData.mode.total=reData.mode.number*reData.mode.outprice;
						 $('#buyProduct').datagrid('insertRow',{row:reData.mode});
						 ysk();
					}else
					{
						$.alert(parent.$,"已存在该产品！！");
					}
				}else
				{
					$.alert(parent.$,reData.msg);
				}
				
			}
			//计算总价钱
			function sum(n)
			{	
			
				var rows = $("#buyProduct").datagrid("getRows")
				var row = $('#buyProduct').datagrid('getSelected');
				var index=$('#buyProduct').datagrid('getRowIndex', row);
				var sum=n*parseFloat(row.outprice);
				$('#buyProduct').datagrid('updateRow', {
	                index: index,
	                row: {
	                	number:n,
	                	total:sum
	                }
	            });
				$('#buyProduct').datagrid('beginEdit', index);
				ysk();
			}
			//
			function  isHave(probh)
			{
				var rows = $("#buyProduct").datagrid("getRows");
				if(rows.length>0)
				{
					for (var i = 0; i < rows.length; i++) {  
					       //获取指定列  
							 if(rows[i].probh)
							 {
								 if(probh==rows[i].probh)
								 {	
									 return true;
								 } 
							 }
					}
				}
				return false;
				
			}
			//应收款
			function  ysk()
			{
				 var to = 0;  
					var rows = $('#buyProduct').datagrid('getRows');
					 for (var i = 0; i < rows.length; i++) {  
				       //获取指定列  
						 if(rows[i].total)
						 {
							 to +=parseFloat(rows[i]['total']); 
						 }
					 }  
					 $('#receivable').numberbox('setValue',to);
					 $('#proceeds').numberbox('setValue',to);
//				    $("#receivable").val(to);
//				    $("#proceeds").val(to);
			}
			
			
			
			//结算
			
			function  settlement(){
				var ymtype=$("#ymtype").val();
				var rows=$('#buyProduct').datagrid("getRows");
				if(rows != ""){	
					var rowjson=JSON.stringify(rows);
//					var customerName=$('#customerName').val();
//					var customerPhone=$('#customerPhone').val();
//					var customerHybh=$('#customerHybh').val();
					var customerIds=$("#customerIds").val();
					var receivable=$("#receivable").val();
					var proceeds=$("#proceeds").val();
					var orderNumber=$("#orderNumber").val();
					var paymentWay=$('#skfs_select').val();
					var xsr = $('#xsr_select').val();
					var cpbh = $('#cpbh').val();
					/*var zkj=$("#zkj").val();
					if(zkj!=null&&zkj!=""){
						receivable = zkj;
					}*/
				
					if(customerIds!=""){
						var url="/buyProduct/settlement";
						var data={"customerIds":customerIds,"receivable":receivable,"proceeds":proceeds,"orderNumber":orderNumber,"paymentWay":paymentWay,"proInfo":rowjson,"xsr":xsr,"cpbh":cpbh};
						
						var reData = common_ajax.ajaxFunc(url, data);
	 					if(reData!="success")
						{		
	 						$.alert(parent.$,reData);
							 
						}else{
							 $.slideMsg("结算成功", parent.$);
							 //更新顾客协议（疗程是否已购买）
							
							 var cusIds=$('#customerIds').val();
							 //location.reload();
							 if(ymtype=='1'){
								 parent.nodeClick("体重登记",'/binShopService?customerIds='+cusIds);
							 }else{
								 parent.refresh();
								 //parent.nodeClick("减重目标",'/bloseWeight?cusIds='+cusIds);
							 }
							// parent.nodeClick("减重目标",'/bloseWeight?cusIds='+cusIds);
						}
					}else
					{
						 $.alert(parent.$, "请先输入姓名和身份证！！");
					}
				}else{
					$.alert(parent.$, "未购买任何产品，无需结算！！");
				}
			}
			function  arrears()
			{	
				
				$("#proceeds").numberbox({
					onChange: function (n,o) {
						var receivable=$('#receivable').val();
						var proceeds=$('#proceeds').val();
						$('#arrears').numberbox('setValue',receivable-proceeds);
					}
				})
			}
			
			
			